package com.woniu.order.controller;


import com.alipay.api.AlipayApiException;
import com.woniu.model.Result;
import com.woniu.order.dto.DownpaymentDto;
import com.woniu.order.model.TDownpayment;
import com.woniu.order.service.TDownpaymentService;
import com.woniu.order.util.RedisUtil;
import com.woniu.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年06月03日
 */
@RestController
@RequestMapping("/tDownpayment")
@Api(tags = "押金服务接口")
public class TDownpaymentController {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TDownpaymentService tDownpaymentService;

    /**
     * 判断用户信誉分，发起定金支付
     * @return
     */
    @ApiOperation("判断用户信誉积分是否交押金,是则发起押金支付")
    @PostMapping("/payDownpayment")
    public Result<DownpaymentDto> payDownpayment() throws Exception {
        HttpServletRequest req =  ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = req.getHeader("token");
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,"jlsdjfksdninfghfdgnkjnsuihfjsammjiaakiakaakakk").get("accountId").toString());
        DownpaymentDto t = tDownpaymentService.payDownpayment(userId);
        return  Result.newInstance(DownpaymentDto.class).setData(t).setMessage("发起支付成功");
    }

    /**
     * 支付押金的异步回调
     * @return 返回"SUCCESS"
     */
    @ApiOperation("支付异步回调")
    @PostMapping("/notify")
    public Result<String> payNotify() throws AlipayApiException {

        HttpServletRequest req =  ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        System.out.println("异步回调接口");
        System.out.println("=================================================");
        //异步回调主要代码
        //获取支付宝POST过来的反馈信息
        //在控制层从request取出支付宝传过来的参数
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = req.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String string = tDownpaymentService.payNotify(params);
        return Result.newInstance(String.class).setData(string).setMessage("支付回调成功");
    }

    /**
     * 退押金
     * @param orderNum 订单编号
     * @param token
     * @return 返回阿里响应结果
     * @throws Exception
     */
    @GetMapping("/tui/{orderNum}")
    public Result<String> refund(
            @ApiParam(name = "orderNum",value = "退款订单编，退押金号")
            @PathVariable("orderNum") String orderNum,@RequestHeader String token) throws Exception {
        String refreshToken =redisUtil.get(token);
        int userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,"jlsdjfksdninfghfdgnkjnsuihfjsammjiaakiakaakakk").get("accountId").toString());
        String s = tDownpaymentService.refund(orderNum,userId);
        return Result.newInstance(String.class).setData(s).setMessage("退款成功");
    }

}

